package exp4;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.TreeMap;

public class CountWords {
    public static void main(String[] args) throws RuntimeException {
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        String username = System.getenv ("USERNAME");  // 分录用户的用户名
        String fileName = "C:\\Users\\"+username+"\\Desktop\\ZYH Workplace\\algorithm\\algorithm\\src\\exp4\\test";
        StringBuilder stringBuilder = new StringBuilder();
        try (Scanner sc = new Scanner(new FileReader(fileName))) {
            while (sc.hasNextLine()) {  //按行读取字符串
                String line = sc.nextLine().toLowerCase();;
                stringBuilder.append(line + " ");
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
        String str = stringBuilder.toString();
        String []word = str.split("\\ |\\,|\\. |\\! |\\? ");
        int temp;
        for (int i = 0; i < word.length; i++) {
            if (treeMap.get(word[i]) != null) {
                temp = treeMap.get(word[i]);
            } else {
                temp = 0;
            }
            treeMap.put(word[i], temp+1);
        }
        System.out.println(treeMap);
    }
}
